package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    //新建线程池
    private static final ExecutorService CASH_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) throws InterruptedException {
        Shop shop;
        //空缓存解决缓存穿透
        shop = cacheClient.get(Shop.class, RedisConstants.CACHE_SHOP_KEY, id, this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);


        //逻辑过期解决缓存穿透
         //shop = cacheClient.getWithLogicExpire(Shop.class, RedisConstants.CACHE_SHOP_KEY, id, this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);


        return Result.ok(shop);
    }



    //使用互斥锁实现优化缓存穿透
    /*@Override
    public Result queryById(Long id){
        //先从缓存中查
        Map shopMap = redisTemplate.opsForHash().entries(RedisConstants.CACHE_SHOP_KEY + id);
        if (shopMap.isEmpty()){

            //避免缓存击穿，在查数据时使用lock
            if (!lockup(id)){
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return queryById(id);
            }
            Shop shop = getById(id);
            if (BeanUtil.isEmpty(shop)){
                //避免缓存穿透，设置空缓存
                HashMap hashMap = new HashMap();
                hashMap.put("name","无此商铺");
                redisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_KEY+id,hashMap);
                redisTemplate.expire(RedisConstants.CACHE_SHOP_KEY+id,
                        5, TimeUnit.MINUTES);
                lockout(id);
                return Result.fail("无此商铺");
            }
            //存入缓存 设置缓存时间
            redisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_KEY+id, BeanUtil.beanToMap(shop));
            redisTemplate.expire(RedisConstants.CACHE_SHOP_KEY+id,
                    RedisConstants.CACHE_NULL_TTL, TimeUnit.HOURS);
            lockout(id);
            return Result.ok(shop);
        }
        if (shopMap.get("name").equals("无此商铺")){
            return Result.fail("无此商铺");
        }
        return Result.ok(BeanUtil.fillBeanWithMap(shopMap,new Shop(),false));
    }*/

    //使用逻辑过期优化缓存击穿
    /*@Override
    public Result queryById(Long id) throws InterruptedException {
        //1.先从缓存中查数据
        Map entries = redisTemplate.opsForHash().entries(RedisConstants.CACHE_SHOP_KEY + id);
        //2.1无数据 从数据库尝试加载
        if (entries.isEmpty()||entries==null){
            Shop shop = this.getById(id);
            if (shop==null){
                //3.1数据库中无数据，防止缓存穿透，放入空数据
                HashMap<Object, Object> hashMap = new HashMap<>();
                hashMap.put("name","无此店铺");
                RedisData data = new RedisData();
                data.setData(hashMap);
                redisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_KEY+id,BeanUtil.beanToMap(data));
                redisTemplate.expire(RedisConstants.CACHE_SHOP_KEY+id,180l,TimeUnit.SECONDS);
                return Result.fail("无此店铺");
            }
            //3.2将数据库中查出数据放入缓存中并返回
            this.saveShop2Redis(id,20l);
            return Result.ok(shop);
        }else if(BeanUtil.beanToMap(entries.get("data")).get("name").equals("无此店铺")){
            return Result.fail("无此店铺");
        }
        //2.2有数据看数据是否过期
        RedisData data = BeanUtil.fillBeanWithMap(entries,new RedisData(),true);
        //填充LocalDataTime时会出现时差异常暂时无法解决，故采用String作为中转
        String expireTime = entries.get("expireTime").toString();
        data.setExpireTime(LocalDateTime.parse(expireTime));
        Shop shop =BeanUtil.toBean(data.getData(),Shop.class) ;
        //2.3数据过期尝试抢锁加载
        if (data.getExpireTime().isBefore(LocalDateTime.now())){
            //2.4抢锁 新起线程查数据
            if(this.lockup(id)){
                this.CASH_REBUILD_EXECUTOR.submit(()->{
                    //重建缓存
                    this.saveShop2Redis(id,20l);
                    this.lockout(id);
                });
            }
        }
        return Result.ok(shop);
    }*/



    /**
     * 更新店铺，加入缓存逻辑，保持数据库与缓存一致性
     * */
    @Override
    public Result updateShop(Shop shop) {
        updateById(shop);
        //删除缓存
        redisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, String x, String y) {
        if (x==null||y==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        long from = (current - 1) * SystemConstants.MAX_PAGE_SIZE;
        long end = current * SystemConstants.MAX_PAGE_SIZE;
        //有经纬度按照经纬度查
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(RedisConstants.SHOP_GEO_KEY + typeId,
                GeoReference.fromCoordinate(Double.parseDouble(x), Double.parseDouble(y)),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if (results==null){
            Result.ok(Collections.EMPTY_LIST);
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        if (content.size()<from) {
            Result.ok(Collections.EMPTY_LIST);
        }
        //获取信息
        List<Long> ids = new ArrayList<>();
        HashMap<Long, Distance> map = new HashMap<>();
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = content.stream().skip(from).collect(Collectors.toList());
        if (list.isEmpty()||list==null){
            return Result.ok(Collections.EMPTY_LIST);
        }
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> location : list) {
            long ShopId = Integer.valueOf(location.getContent().getName());
            map.put(ShopId,location.getDistance());
            ids.add(ShopId);
        }
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = this.lambdaQuery().in(Shop::getId, ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        shops.forEach(shop ->shop.setDistance(map.get(shop.getId()).getValue()));

        return Result.ok(shops);
    }


    //缓存重建
    private void saveShop2Redis(Long id,Long expireSeconds){
        RedisData data = new RedisData();
        data.setData(this.getById(id));
        data.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        redisTemplate.opsForHash().putAll(RedisConstants.CACHE_SHOP_KEY+id,BeanUtil.beanToMap(data));
    }

    //加锁
    private  boolean lockup(Long id){
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(RedisConstants.LOCK_SHOP_KEY + id, "1");
        return BooleanUtil.isTrue(aBoolean);
    }

    //解锁
    private boolean lockout(Long id){
        Boolean delete = redisTemplate.delete(RedisConstants.LOCK_SHOP_KEY + id);
        return BooleanUtil.isTrue(delete);
    }
}
